/**
 * Created by admin on 2017/9/13.
 */
define([
    "helpers/network",
    "libs/md5",
    "models/user",
    "models/commonStatus",
    "models/roles",
    "views/modules/popup",
    "views/modules/form",
    "views/modules/table",
    "views/modules/pager"
], function (Network, md5, User, CommonStatus, Roles, PopupView, CommonForm, CommonTable, CommonPager) {
    var TYPE = "Admin";
    var id = "";
    var keywordsId = id + "keywordsId";
    var windowsId = id + "window";
    var formId = id + "form";
    var searchFormId = id + "searchForm";
    var freezeBtnId = id + "freeze";
    var tableId = id + "table";
    var pagerId = id + "pager";
    var totalCountsId = id + "totalCounts";
    var pageIndex = 1, pageCounts;

    var onTableReady = function (page) {
        // var searchForm = $$(searchFormId).getValues();
        var obj = {
            params: {
                // data: {
                //     name: searchForm[keywordsId] || undefined
                // },
                type: TYPE
            },
            page: page || 1,
            sort: ["creationTime,desc"]
        };
        Network.ajax("/BizView.queryAll.query", obj, function (ret) {
            $$(tableId).clearAll();
            $$(tableId).parse(ret.data.content);
            pageCounts = ret.data.totalPages;
            if (!page) {
                $$(pagerId).config.page = 0;
            }
            $$(pagerId).define("count", pageCounts || 1);
            $$(pagerId).refresh();
            $$(totalCountsId).setValue(ret.data.totalElements + "条数据, 共" + pageCounts + "页");
        });
    };

    var onSubmit = function (itemId) {
        if (!$$(formId).validate()) {
            webix.message("信息填写有误, 请仔细录入...");
            return
        }
        var itemValues = $$(formId).getValues();
        itemValues.lastModifyTime = new Date();
        if (itemValues.password) {
            itemValues.password = md5(md5(itemValues.password));
        } else {
            itemValues.password = undefined
        }

        var obj = {
            data: {
                id: itemId || undefined,
                type: TYPE,
                data: itemValues,
                check: {
                    unique: ["username"]
                    // "ge":["balance:0"]
                }
            }
        };

        Network.ajax("/BizTransactor.save.command", obj, function (ret) {
            closeWindow();
            onTableReady();
        })
    };

    var closeWindow = function () {
        if ($$(windowsId)) {
            $$(windowsId).close();
        }
        // if (uEditor) {
        //     uEditor.destroy();
        // }
    };

    var onWindowReady = function (item) {
        // uEditor = UE.getEditor(uEditorId, uEditorConfig);
        // uEditor.addListener('ready', function (state) {
        //     if (item && item.content) {
        //         uEditor.setContent(item.content.toApiUrlImageSrcContent());
        //     }
        // });
    };

    var showWindow = function (title, item) {
        item = item || {data: {}};
        PopupView(windowsId, title, {
            rows: [
                {
                    view: "scrollview", scroll: "y", paddingY: 5, paddingX: 10,
                    body: {
                        rows: [
                            {
                                view: "form", borderless: true, id: formId,
                                elements: [
                                    {
                                        label: "用户名称", name: "value", view: "text",
                                        required: true, value: item.data.value || ""
                                    },
                                    {
                                        label: "登录名", name: "username", view: "text",
                                        required: true, value: item.data.username || ""
                                    },
                                    {
                                        label: "登录密码", name: "password", view: "text", hidden: item.data.username,
                                        required: true, value: item.data.password || ""
                                    },
                                    {
                                        label: "联系方式", name: "contact", view: "text",
                                        required: true, value: item.data.contact || ""
                                    },
                                    CommonForm.genSingleOptionSelector("status", "状态", CommonStatus.userStatus, item.data["status"], true),
                                    CommonForm.genSingleOptionSelector("role", "角色", Roles.data, item.data["role"], true),
                                    // CommonForm.genSingleOptionSelector("supplier", "供应商", Supplier.data, item.data["supplier"], true),
                                    {
                                        label: "备注", name: "remark", view: "text",
                                        value: item.data.remark || ""
                                    },
                                    {}
                                ]
                            }]
                    }
                },
                CommonForm.genSubmitButton(function () {
                    onSubmit(item.id)
                })
            ]
        }, 600, 570, function () {
            onWindowReady(item)
        }, closeWindow);
    };

    var freeze = function (item) {
        var statusObj = _.find(CommonStatus.userStatus, function (each) {
            return each.id !== item.data.status.id
        });
        var oppositeStatusObj = _.find(CommonStatus.userStatusAction, function (each) {
            return each.id === item.data.status.id
        });
        var obj = {
            data: {
                id: item.id,
                type: TYPE,
                data: {
                    status: statusObj,
                    lastModifyTime: new Date()
                }
            }
        };
        // item.data.status = statusObj;
        Network.ajax("/BizTransactor.save.command", obj, function (ret) {
            onTableReady(pageIndex)
            // $$(tableId).updateItem(item.id, item);
            // $$(freezeBtnId).setValue(oppositeStatusObj.value);
            // $$(freezeBtnId).refresh();
        });
    };

    var genSearchFormUI = function () {
        return {
            id: searchFormId, view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
            cols: [
                {},
                {
                    id: "static", name: "static", view: "select", width: 100, css: {"text-align": "center"},
                    value: "id",
                    options: User.userSearchTypes
                },
                CommonForm.genKeywordsUI(keywordsId, "依据左边状态查询", onTableReady),
                CommonForm.genQueryButtonUI(onTableReady)
            ]
        }
    };

    var genOperationFormUI = function () {
        return {
            view: formId, css: "toolbar", paddingY: 5, paddingX: 10,
            cols: [
                {view: "label", label: "操作"},
                {
                    view: "button", label: "创建", width: 90,
                    // hidden: Authority.hasNoAuth("GOODS_MODIFY"),
                    click: function () {
                        showWindow("添加")
                    }
                },
                {
                    id: freezeBtnId, view: "button", value: "冻结/启用",
                    // hidden: Authority.hasNoAuth("GOODS_ONLINE"),
                    width: 90,
                    click: function () {
                        var item = $$(tableId).getSelectedItem();
                        if (item) freeze(item)
                    }
                },
                {
                    view: "button", value: "修改",
                    // hidden: Authority.hasNoAuth("GOODS_ONLINE"),
                    width: 90,
                    click: function () {
                        var item = $$(tableId).getSelectedItem();
                        if (item) showWindow("修改", item)
                    }
                }
            ]
        }
    };

    var genDataTableUI = function () {
        return {
            id: tableId, view: "datatable", resizeColumn: true, complexData: true, select: "row", data: [],
            ready: onTableReady,
            on: {
                onItemClick: function (id) {
                    var item = this.getItem(id);
                    if (item.data.status.id === "disabled") {
                        $$(freezeBtnId).setValue("启用");
                    } else if (item.data.status.id === "enabled") {
                        $$(freezeBtnId).setValue("冻结");
                    }
                    $$(freezeBtnId).refresh();
                }
            },
            columns: [
                {
                    id: "id", header: "用户ID"
                },
                {
                    id: "username", header: "账号", fillspace: true,
                    template: "#data.username#"
                },
                {
                    id: "name", header: "姓名", fillspace: true,
                    template: "#data.value#"
                },
                {
                    id: "status", header: "状态",
                    template: "#data.status.value#"
                },
                {
                    id: "role", header: "角色",
                    template: "#data.role.value#"
                },
                // {
                //     id: "role", header: "所属供应商", fillspace: true,
                //     template: "#data.supplier.value#"
                // },
                // {
                //     id: "id3", header: "管理组", fillspace: true,
                //     template: "#data.name#"
                // },
                CommonTable.genLastModifyTimeColumn()
            ]
        }
    };

    var genFooterUI = function () {
        return {
            cols: [
                CommonPager.genPagerUI(pagerId, pageIndex, pageCounts, onTableReady),
                CommonPager.genTotalCountsUI(totalCountsId), {}
            ]
        }
    };

    return {
        $ui: {
            padding: 10,
            rows: [
                // genSearchFormUI(),
                genOperationFormUI(),
                genDataTableUI(),
                genFooterUI()
            ]
        }
    };
});